package servlet;

import dao.UserDao;
import model.User;
import utils.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 功能描述
 *
 * @author wileda
 * @date 2023/04/10  16:45
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=utf-8");

        //接收参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //非空校验
        if(StringUtil.isEmpty(username) || StringUtil.isEmpty(password)){
            resp.getWriter().write("用户名密码不能为空");
            return;
        }
        //数据库查询
        //通过传入的用户名查询用户信息
        UserDao  userDao = new UserDao();
        User user = userDao.selectByUsername(username);
        if(user == null){
            resp.getWriter().write("用户名或密码错误");
            return;
        }
        //对比数据中的用户密码与传入的密码是否相同，不同响应错误信息
        if(!user.getPassword().equals(password)){
            //密码不相同
            resp.getWriter().write("用户名或密码错误");
            return;
        }
        //如果相同则校验通过，在session中保存用户信息
        //获取Session,如果session不存在 则创建一个新的session
        HttpSession session = req.getSession(true);
        //把用户信息设置到session中
        session.setAttribute("userInfo", user);
        //跳转到博客列表页
        resp.sendRedirect("blog_list.html");


    }
}
